package com.ad.platform.service.impl;

import com.ad.payload.dto.MerchantDto;
import com.ad.payload.dto.merchant.ItemDetailPageDto;
import com.ad.payload.enums.BusinessTypeEnum;
import com.ad.payload.model.IdDto;
import com.ad.payload.model.PageView;
import com.ad.payload.util.ObjectUtil;
import com.ad.payload.util.StringUtil;
import com.ad.payload.vo.DetailKeyValue;
import com.ad.payload.vo.eatService.EatServiceVo;
import com.ad.payload.vo.item.ItemImgVo;
import com.ad.payload.vo.merchant.ItemCategoryVo;
import com.ad.payload.vo.merchant.ItemCoverVo;
import com.ad.payload.vo.merchant.MerchantVo;
import com.ad.platform.common.utils.BeanUtil;
import com.ad.platform.mapper.*;
import com.ad.platform.model.*;
import com.ad.platform.service.IMerchantService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author:dxgong
 * @日期 2021/3/25 14:25
 * @注释
 */
@Service
@Slf4j
public class MerchantServiceImpl implements IMerchantService {

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private EatServiceMapper eatServiceMapper;

    @Autowired
    private MerchantDetailKeyValMapper merchantDetailKeyValMapper;

    @Autowired
    private ItemCategoryMapper itemCategoryMapper;

    @Autowired
    private ItemDetailMapper itemDetailMapper;

    @Autowired
    private UploadRecordMapper uploadRecordMapper;

    /**
     * 查询商家信息
     *
     * @param idDto
     */
    @Override
    public MerchantVo queryMerchantDetail(IdDto idDto) {
        Merchant merchant = merchantMapper.selectById(idDto.getId());

        MerchantVo vo = new MerchantVo();
        BeanUtil.copyProperties(merchant, vo);

        QueryWrapper<MerchantDetailKeyVal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", idDto.getId()).orderByAsc("id");

        List<MerchantDetailKeyVal> merchantDetailKeyVals = merchantDetailKeyValMapper.selectList(queryWrapper);
        List<DetailKeyValue> list = new ArrayList<>();

        merchantDetailKeyVals.forEach(item -> {
            DetailKeyValue detailKeyValue = new DetailKeyValue();
            detailKeyValue.setId(String.valueOf(item.getId()));
            detailKeyValue.setKey(item.getItemKey());
            detailKeyValue.setValue(item.getItemValue());
            list.add(detailKeyValue);
        });

        vo.setDetailList(list);

        return vo;
    }

    /**
     * 查询当前商家的产品分类
     *
     * @param idDto
     */
    @Override
    public List<ItemCategoryVo> queryMerchantCategory(IdDto idDto) {
        QueryWrapper<ItemCategory> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("merchant_id", idDto.getId()).orderByDesc("id");
        List<ItemCategory> itemCategories = itemCategoryMapper.selectList(queryWrapper);

        List<ItemCategoryVo> rtnList = new ArrayList<>();

        // 添加【全部】标签，id是0
        ItemCategoryVo itemCategoryVo = new ItemCategoryVo();
        itemCategoryVo.setId(String.valueOf(0));
        itemCategoryVo.setName("全部");
        rtnList.add(itemCategoryVo);
        itemCategories.forEach(item -> {
            ItemCategoryVo vo = new ItemCategoryVo();
            vo.setId(String.valueOf(item.getId()));
            vo.setName(item.getName());
            rtnList.add(vo);
        });

        return rtnList;
    }

    /**
     * 根据产品分类ID产品分页列表
     *
     * @param itemDetailPageDto
     */
    @Override
    public PageView<ItemCoverVo> pageListItemDetail(ItemDetailPageDto itemDetailPageDto) {
        QueryWrapper<ItemDetail> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq(StringUtil.isNotBlank(String.valueOf(itemDetailPageDto.getClassId())) && !itemDetailPageDto.getClassId().equals(0L), "class_id", itemDetailPageDto.getClassId())
                .eq(StringUtil.isNotBlank(String.valueOf(itemDetailPageDto.getMerchantId())), "merchant_id", itemDetailPageDto.getMerchantId())
                .orderByDesc("id");

        IPage<ItemDetail> itemDetailIPage = itemDetailMapper.selectPage(new Page<>(itemDetailPageDto.getPageNo(), itemDetailPageDto.getPageSize()), queryWrapper);
        PageView pageView = new PageView(itemDetailIPage);
        List<ItemCoverVo> rtnList = new ArrayList<>();
        itemDetailIPage.getRecords().forEach(item -> {
            ItemCoverVo itemCoverVo = new ItemCoverVo();
            BeanUtil.copyProperties(item, itemCoverVo);
            itemCoverVo.setId(String.valueOf(item.getId()));

            // 查询产品照片, 以第一张上传为封面
            QueryWrapper<UploadRecord> uploadRecordQueryWrapper = new QueryWrapper<>();
            uploadRecordQueryWrapper.eq("business_id", item.getId()).orderByAsc("id");
            List<UploadRecord> uploadRecords = uploadRecordMapper.selectList(uploadRecordQueryWrapper);
            if(uploadRecords.size() != 0){
                UploadRecord uploadRecord = uploadRecords.get(0);
                itemCoverVo.setItemCover(uploadRecord.getPath());
            }
            rtnList.add(itemCoverVo);
        });

        pageView.setPageList(rtnList);
        return pageView;
    }

    @Override
    public PageView<MerchantVo> listPageMerchantForIndex(MerchantDto merchantDto) {

        IPage<Merchant> page = new Page(merchantDto.getPageNo(), merchantDto.getPageSize());
        IPage<Map<String, Object>> merchantIPage = merchantMapper.selectPageIndex(
                page,
                merchantDto.getLatitude(),
                merchantDto.getLongitude(),
                merchantDto.getCityCode(),
                merchantDto.getTown(),
                merchantDto.getName(),
                null,
                merchantDto.getFirstCategoryId(), merchantDto.getSecondCategoryId());

        // 通过Ipage实例化pageView
        PageView pageView = new PageView(merchantIPage);

        List<MerchantVo> rtnList = new ArrayList();
        List<Long> longs = new ArrayList<>();
        merchantIPage.getRecords().forEach(item -> {
            MerchantVo vo = new MerchantVo();
            ObjectUtil.mapToObj(item,vo);
            String s = distanceHandle(vo.getDistance());
            vo.setDistanceDesc(s);
            rtnList.add(vo);
            longs.add(vo.getId());
        });

        //查询eatService
        if(longs.size() != 0){
            QueryWrapper<EatService> eatServiceQueryWrapper = new QueryWrapper<>();
            eatServiceQueryWrapper.in("merchant_id",longs);
            eatServiceQueryWrapper.eq("status","Y");
            List<EatService> eatServices = eatServiceMapper.selectList(eatServiceQueryWrapper);
            for(int i = 0; i < rtnList.size(); i++){
                List<EatServiceVo> eatServiceVos = new ArrayList<>();
                for(int k = 0; k < eatServices.size(); k++){
                    if(rtnList.get(i).getId() == eatServices.get(k).getMerchantId()){
                        EatServiceVo eatServiceVo = new EatServiceVo();
                        eatServiceVo.setTitle(eatServices.get(k).getTitle());
                        eatServiceVo.setOrderType(eatServices.get(k).getOrderType());
                        eatServiceVos.add(eatServiceVo);
                    }
                    if(k == eatServices.size() - 1){
                        rtnList.get(i).setEatServices(eatServiceVos);
                    }
                }
            }
        }


        pageView.setPageList(rtnList);

        return pageView;
    }

    /**
     * 查询商品的封面图，详情图
     *
     * @param idDto
     */
    @Override
    public ItemImgVo queryItemImg(IdDto idDto) {
        QueryWrapper<UploadRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("business_id", idDto.getId());
        List<UploadRecord> uploadRecords = uploadRecordMapper.selectList(queryWrapper);
        List<String> coverList = new ArrayList<>();
        if(uploadRecords.isEmpty()){
            ItemImgVo imgVo = new ItemImgVo();
            imgVo.setCoverList(new ArrayList<>());
            imgVo.setDetailList(new ArrayList<>());
            return imgVo;
        }
        uploadRecords.stream().filter(predicate -> BusinessTypeEnum.ITEM_COVER.getValue().equals(predicate.getBusinessType())).forEach(item -> {
            coverList.add(item.getPath());
        });
        ItemImgVo imgVo = new ItemImgVo();
        imgVo.setCoverList(coverList);
        List<String> detailList = new ArrayList<>();
        uploadRecords.stream().filter(predicate -> BusinessTypeEnum.DETAIL.getValue().equals(predicate.getBusinessType())).forEach(item -> {
            detailList.add(item.getPath());
        });

        imgVo.setDetailList(detailList);
        return imgVo;
    }

    private String distanceHandle(Double l){
        if(l > 1500) {
            if (l > 3000) {
                if (l > 5000) {
                    return ">5.0km";
                } else {
                    return ">3.0km";
                }
            } else {
                return ">1.5km";
            }
        } else {
            return l+"m";
        }
    }



}
